package controller

import (
	bc "accurchain.com/supplychain-finance/application/blockchain"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
)

/**
  @Author: dd
  @Date:   2020/5/13 11:50
  @Desc:   登录, 不做考察要求，因为登录可能使用token或者session不在考察范围内，而且fabric-ca是提供了用户权限管理的功能的，暂且用验证账号密码的方式实现简单的登录
  @Param:
  @Return:
**/
func Login(ctx *gin.Context) {

	var company Company
	err := ctx.ShouldBind(&company)
	if err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if company.Account == "" || company.Password == "" ||
		(company.CompanyType != "financial_org" && company.CompanyType != "supplier" && company.CompanyType != "buyer") {
		ctx.String(http.StatusUnauthorized, "账号名或密码错误或错误的企业类型")
		return
	}
	var companys []Company
	resp, err := bc.ChannelQuery("getCompany", [][]byte{
		[]byte(company.CompanyType),
	})

	if err != nil {
		ctx.String(int(resp.ChaincodeStatus), err.Error())
		return
	}
	err = json.Unmarshal(resp.Payload, &companys)
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	for _, v := range companys {
		if v.Account == company.Account && v.Password == company.Password {
			company.Password = ""
			ctx.JSON(http.StatusOK, v)
			return
		}
	}
	ctx.String(http.StatusUnauthorized, "账号名或密码错误")

}
